package com.qcby.llmtchstd.websocket;

import com.qcby.llmtchstd.entity.User;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Component
public class ChatHandshakeInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if(request instanceof ServletServerHttpRequest){
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpSession session = servletRequest.getServletRequest().getSession(false);
            if(session.getAttribute("loginUser") !=null){
                User loginUser = (User) session.getAttribute("loginUser");
                attributes.put("loginUser",loginUser);
                System.out.println("Websocket:用户[ID:" + (loginUser.getId() + ",Name:"+loginUser.getName()+"]要建立连接"));
            }else{
                System.out.println("--------------握手已失败...");
                return false;
            }
        }
        System.out.println("--------------握手开始...");
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
        System.out.println("--------------握手成功啦...");
    }
}
